package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.model.behavior.dtos.CollectionBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.exception.CustException;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadLocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {
    @Autowired
    private ApBehaviorEntryServiceImpl apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult collectBehavior(CollectionBehaviorDTO dto) {
        // 1 校验参数  文章id不能null  操作类型 0 或 1
        // 1.1 需要登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "当前用户未登录!");
        }
        // 2 根据userId查询行为实体数据
        Integer id = user.getId();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(id, null);
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体对象不存在或者创建失败!");
        }
        // 3 如果是收藏操作 判断是否已经收藏
        if (ApCollection.Type.ARTICLE.getCode() == dto.getOperation()) {
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));
            ApCollection apCollection = mongoTemplate.findOne(query, ApCollection.class);
            if (apCollection != null) {
                // 收藏过了
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "已经收藏过了");
            }
            //如果未收藏 新增收藏行为
            ApCollection newApCollection = new ApCollection();
            newApCollection.setCollectionTime(new Date());
            newApCollection.setArticleId(dto.getArticleId());
            newApCollection.setEntryId(apBehaviorEntry.getId());
            newApCollection.setType(ApCollection.Type.ARTICLE.getCode());
            ApCollection save = mongoTemplate.save(newApCollection);
            System.out.println(save);
        } else {
            //如果是取消收藏操作  删除收藏行为
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));
            DeleteResult remove = mongoTemplate.remove(query);
            System.out.println(remove);
        }
        // 发送新行为消息
        NewBehaviorDTO newBehavior = new NewBehaviorDTO();
        int add = dto.getOperation().intValue() == 0 ? 1 : -1;
        newBehavior.setAdd(add);
        newBehavior.setType(NewBehaviorDTO.BehaviorType.COLLECTION);
        newBehavior.setArticleId(dto.getArticleId());
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(newBehavior));
        log.info("成功发送 文章收藏行为消息,消息内容: {}", newBehavior);
        return ResponseResult.okResult();
    }
}
